
package com.zsrt.day20170504.ch08;


public class ProducerConsumer {

	public static void main(String[] args) {
		SyncStack syncStack = new SyncStack();
		
		Producer producer= new Producer(syncStack);
		Consumer consumer= new Consumer(syncStack);
		
		new Thread(producer).start();
		new Thread(consumer).start();
	}
}

class MoTou{
	int id;
	
	public MoTou(int id) {
		this.id= id;
	}
	public String toString(){
		return "第"+id+"个馒头";
	}
}

class SyncStack{
	int index = 1;
	//一次生产
	MoTou[] arrMT = new MoTou[6];
	
	public synchronized void push(MoTou mt){
		if(index==arrMT.length){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//唤醒
		this.notifyAll();
		arrMT[index] = mt;
		index++;
	}
	
	public synchronized MoTou  pop(){
		//判断条件 到底要剩几个
		while(index<=3){
			try {
				System.out.println("馒头不足");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
			
		this.notify();
		index--;
		return arrMT[index];
		
	}
}

/**
 * 生产者
 * @author jmj
 * @date 2017年5月4日
 * @time 下午8:05:47
 */
class Producer implements Runnable{
	 SyncStack ss = null;
	 
	 Producer(SyncStack ss){
		 this.ss = ss;
	 }

	@Override
	public void run() {
		for(int i=1;i<=20;i++){
			MoTou  mt = new MoTou(i);
			ss.push(mt);
			System.out.println("生产了：" + mt);
			
		}
	}
	 
}

/**
 * 消费者
 */
class Consumer implements Runnable{
	SyncStack ss = null;
	public Consumer(SyncStack ss) {
		this.ss = ss;
	}
	
	@Override
	public void run() {
		for(int i=1;i<=20;i++){
			MoTou mt = ss.pop();
			
			System.out.println("消费了："+mt);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}